package demo1;

import java.util.Arrays;

public class MyStack<E> {
    private Object[] elem;
    private int useSize;
    public static final int DEFAULT_CAPACITY = 10;

    public MyStack() {
        elem = new Object[DEFAULT_CAPACITY];
    }

    /**
     * 完成入栈操作
     */
    public void push(E data) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[useSize] = data;
        useSize++;
    }

    /**
     * 完成出栈操作，将栈顶的元素出栈并返回
     */
    public E pop() {
        if(isEmpty()) {
            return null;
        }
        E ret = (E)elem[useSize - 1];
        useSize--;
        return ret;
    }

    /**
     * 返回栈顶的元素
     */
    public E peek() {
        if(elem == null) {
            return null;
        }
        return (E)elem[useSize - 1];
    }

    /**
     * 栈中的元素个数
     * @return
     */
    public int size() {
        return useSize;
    }
    private boolean isFull() {
        return elem.length == useSize;
    }
    public boolean isEmpty() {
        return useSize == 0;
    }
    public void display() {
        for (int i = 0; i < useSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();
    }
}
